package controllers

import (
	"inventory-system/models"
	"strconv"
	"time"

	"github.com/beego/beego/v2/core/logs"
	"github.com/tealeg/xlsx"
)

type ProductController struct {
	BaseController
}

func (c *ProductController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 20)
	search := c.GetString("search")

	var products []models.Product
	var total int64
	var err error

	if search != "" {
		products, total, err = models.SearchProducts(search, page, size)
	} else {
		products, total, err = models.GetAllProducts(page, size)
	}

	if err != nil {
		logs.Error("Failed to get products:", err)
		c.JSONResponse(false, "获取商品列表失败")
		return
	}

	c.Data["Products"] = products
	c.Data["Total"] = total
	c.Data["Page"] = page
	c.Data["PageSize"] = size
	c.Data["Search"] = search
	c.Data["Title"] = "商品管理"
	c.TplName = "products.tpl"
}

func (c *ProductController) Add() {
	if !c.Ctx.Input.IsPost() {
		c.JSONResponse(false, "非法请求")
		return
	}

	uniqueCode := c.GetString("unique_code")
	name := c.GetString("name")
	priceStr := c.GetString("price")

	// 验证唯一码
	if !models.ValidateUniqueCode(uniqueCode) {
		c.JSONResponse(false, "唯一码必须是16位字母数字组合")
		return
	}

	// 检查唯一码是否已存在
	exists, err := models.IsUniqueCodeExists(uniqueCode)
	if err != nil {
		logs.Error("Failed to check unique code:", err)
		c.JSONResponse(false, "系统错误")
		return
	}
	if exists {
		c.JSONResponse(false, "唯一码已存在")
		return
	}

	// 验证价格
	price, err := strconv.ParseFloat(priceStr, 64)
	if err != nil || price < 0 {
		c.JSONResponse(false, "价格格式错误")
		return
	}

	product := models.Product{
		UniqueCode:  uniqueCode,
		Name:        name,
		Price:       price,
		StorageTime: time.Now(),
		Status:      "in_storage",
	}

	err = product.Save()
	if err != nil {
		logs.Error("Failed to add product:", err)
		c.JSONResponse(false, "添加商品失败")
		return
	}

	c.JSONResponse(true, "添加成功")
}

func (c *ProductController) Update() {
	if !c.Ctx.Input.IsPost() {
		c.JSONResponse(false, "非法请求")
		return
	}

	uniqueCode := c.GetString("unique_code")
	name := c.GetString("name")
	priceStr := c.GetString("price")

	product, err := models.GetProductByCode(uniqueCode)
	if err != nil {
		c.JSONResponse(false, "商品不存在")
		return
	}

	price, err := strconv.ParseFloat(priceStr, 64)
	if err != nil || price < 0 {
		c.JSONResponse(false, "价格格式错误")
		return
	}

	product.Name = name
	product.Price = price

	err = models.UpdateProduct(product)
	if err != nil {
		logs.Error("Failed to update product:", err)
		c.JSONResponse(false, "更新商品失败")
		return
	}

	c.JSONResponse(true, "更新成功")
}

func (c *ProductController) Delete() {
	if !c.Ctx.Input.IsPost() {
		c.JSONResponse(false, "非法请求")
		return
	}

	code := c.GetString("code")
	err := models.DeleteProduct(code)
	if err != nil {
		logs.Error("Failed to delete product:", err)
		c.JSONResponse(false, "删除商品失败")
		return
	}

	c.JSONResponse(true, "删除成功")
}

func (c *ProductController) Sell() {
	if !c.Ctx.Input.IsPost() {
		c.JSONResponse(false, "非法请求")
		return
	}

	code := c.GetString("code")
	product, err := models.GetProductByCode(code)
	if err != nil {
		c.JSONResponse(false, "商品不存在")
		return
	}

	if product.Status == "sold" {
		c.JSONResponse(false, "商品已出售")
		return
	}

	product.Status = "sold"
	product.OutboundTime = time.Now()

	err = models.UpdateProduct(product)
	if err != nil {
		logs.Error("Failed to sell product:", err)
		c.JSONResponse(false, "出售失败")
		return
	}

	c.JSONResponse(true, "出售成功")
}

func (c *ProductController) Export() {
	products, _, err := models.GetAllProducts(1, 10000)
	if err != nil {
		logs.Error("Failed to get products for export:", err)
		c.Ctx.WriteString("导出失败")
		return
	}

	file := xlsx.NewFile()
	sheet, err := file.AddSheet("商品清单")
	if err != nil {
		logs.Error("Error creating sheet:", err)
		c.Ctx.WriteString("导出失败")
		return
	}

	// 表头
	header := sheet.AddRow()
	header.AddCell().Value = "唯一码"
	header.AddCell().Value = "商品名称"
	header.AddCell().Value = "价格"
	header.AddCell().Value = "入库时间"
	header.AddCell().Value = "出库时间"
	header.AddCell().Value = "状态"

	// 数据
	for _, product := range products {
		row := sheet.AddRow()
		row.AddCell().Value = product.UniqueCode
		row.AddCell().Value = product.Name
		row.AddCell().Value = strconv.FormatFloat(product.Price, 'f', 2, 64)
		row.AddCell().Value = product.StorageTime.Format("2006-01-02 15:04:05")

		if !product.OutboundTime.IsZero() {
			row.AddCell().Value = product.OutboundTime.Format("2006-01-02 15:04:05")
		} else {
			row.AddCell().Value = ""
		}

		if product.Status == "sold" {
			row.AddCell().Value = "已出售"
		} else {
			row.AddCell().Value = "在库"
		}
	}

	c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Ctx.ResponseWriter.Header().Set("Content-Disposition", "attachment; filename=products_"+time.Now().Format("20060102150405")+".xlsx")

	err = file.Write(c.Ctx.ResponseWriter)
	if err != nil {
		logs.Error("Error writing excel file:", err)
		c.Ctx.WriteString("导出失败")
	}
}

func (c *ProductController) CheckUniqueCode() {
	code := c.GetString("code")
	if !models.ValidateUniqueCode(code) {
		c.JSONResponse(false, "唯一码必须是16位字母数字组合")
		return
	}

	exists, err := models.IsUniqueCodeExists(code)
	if err != nil {
		c.JSONResponse(false, "检查失败")
		return
	}

	if exists {
		c.JSONResponse(false, "唯一码已存在")
	} else {
		c.JSONResponse(true, "唯一码可用")
	}
}

func (c *ProductController) GetProductDetail() {
	code := c.GetString("code")
	product, err := models.GetProductByCode(code)
	if err != nil {
		c.JSONResponse(false, "获取商品详情失败")
		return
	}

	c.JSONResponse(true, "获取成功", product)
}
